<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FastAPI 文本问答系统 - 演示</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 32px;
        }
        
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        .section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }
        
        .section h2 {
            color: #333;
            margin-bottom: 15px;
            font-size: 20px;
        }
        
        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-area:hover {
            background: #f0f0ff;
            border-color: #764ba2;
        }
        
        input[type="file"] {
            display: none;
        }
        
        input[type="text"] {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        input[type="text"]:focus {
            outline: none;
            border-color: #667eea;
        }
        
        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: transform 0.2s;
            margin-top: 10px;
        }
        
        button:hover {
            transform: translateY(-2px);
        }
        
        button:active {
            transform: translateY(0);
        }
        
        .status {
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
            font-size: 14px;
        }
        
        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .answer-box {
            background: white;
            border: 2px solid #667eea;
            border-radius: 10px;
            padding: 20px;
            margin-top: 15px;
            min-height: 100px;
            white-space: pre-wrap;
            line-height: 1.6;
        }
        
        .context-box {
            background: #fff9e6;
            border: 1px solid #ffd700;
            border-radius: 8px;
            padding: 15px;
            margin-top: 10px;
            font-size: 13px;
        }
        
        .context-item {
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px dashed #ddd;
        }
        
        .context-item:last-child {
            border-bottom: none;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 FastAPI 文本问答系统</h1>
        <p class="subtitle">基于 OpenAI Embedding 和 Chat API 的智能问答演示</p>
        
        <!-- 文件上传 -->
        <div class="section">
            <h2>📄 步骤 1: 上传文本文件</h2>
            <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                <p>点击选择 .txt 文件上传</p>
                <p style="font-size: 12px; color: #999; margin-top: 5px;">支持 UTF-8 编码的文本文件</p>
            </div>
            <input type="file" id="fileInput" accept=".txt" onchange="uploadFile()">
            <div id="uploadStatus"></div>
        </div>
        
        <!-- 知识库状态 -->
        <div class="section">
            <h2>📊 步骤 2: 查看知识库状态</h2>
            <button onclick="checkStatus()">刷新状态</button>
            <div id="statusInfo"></div>
        </div>
        
        <!-- 提问 -->
        <div class="section">
            <h2>💬 步骤 3: 提问</h2>
            <input type="text" id="questionInput" placeholder="输入你的问题，例如：这段文本主要讲了什么？" 
                   onkeypress="if(event.key==='Enter') askQuestion()">
            <button onclick="askQuestion()">提交问题</button>
            <div id="answerBox"></div>
        </div>
    </div>
    
    <script>
        const BASE_URL = 'http://localhost:8000';
        
        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file) return;
            
            const statusDiv = document.getElementById('uploadStatus');
            statusDiv.innerHTML = '<div class="status info">正在上传和处理文件... <span class="loading"></span></div>';
            
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                const response = await fetch(`${BASE_URL}/api/v1/text/upload`, {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    statusDiv.innerHTML = `
                        <div class="status success">
                            <strong>✅ 上传成功！</strong><br>
                            文件名: ${data.filename}<br>
                            文本块数: ${data.chunk_count}<br>
                            总字符数: ${data.total_characters}<br>
                            处理耗时: ${data.processing_time} 秒
                        </div>
                    `;
                    checkStatus();
                } else {
                    statusDiv.innerHTML = `<div class="status error">❌ 上传失败: ${data.detail}</div>`;
                }
            } catch (error) {
                statusDiv.innerHTML = `<div class="status error">❌ 错误: ${error.message}</div>`;
            }
        }
        
        async function checkStatus() {
            const statusDiv = document.getElementById('statusInfo');
            statusDiv.innerHTML = '<div class="status info">加载中... <span class="loading"></span></div>';
            
            try {
                const response = await fetch(`${BASE_URL}/api/v1/knowledge/status`);
                const data = await response.json();
                
                if (response.ok) {
                    const lastUpdated = data.last_updated ? 
                        new Date(data.last_updated * 1000).toLocaleString('zh-CN') : '未知';
                    
                    statusDiv.innerHTML = `
                        <div class="status ${data.is_initialized ? 'success' : 'info'}">
                            <strong>📚 知识库状态</strong><br>
                            文档总数: ${data.total_documents}<br>
                            文本块总数: ${data.total_chunks}<br>
                            总字符数: ${data.total_characters}<br>
                            最后更新: ${lastUpdated}<br>
                            Embedding 模型: ${data.embedding_model}<br>
                            状态: ${data.is_initialized ? '✅ 已初始化' : '⚠️ 未初始化'}
                        </div>
                    `;
                } else {
                    statusDiv.innerHTML = `<div class="status error">❌ 获取状态失败</div>`;
                }
            } catch (error) {
                statusDiv.innerHTML = `<div class="status error">❌ 错误: ${error.message}</div>`;
            }
        }
        
        async function askQuestion() {
            const questionInput = document.getElementById('questionInput');
            const question = questionInput.value.trim();
            
            if (!question) {
                alert('请输入问题');
                return;
            }
            
            const answerBox = document.getElementById('answerBox');
            answerBox.innerHTML = `
                <div class="answer-box">
                    <div style="color: #999;">正在思考... <span class="loading"></span></div>
                </div>
            `;
            
            try {
                const response = await fetch(`${BASE_URL}/api/v1/chat/query`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream'
                    },
                    body: JSON.stringify({ question })
                });
                
                if (!response.ok) {
                    const error = await response.json();
                    answerBox.innerHTML = `<div class="status error">❌ ${error.detail}</div>`;
                    return;
                }
                
                let answer = '';
                let contextData = null;
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                
                answerBox.innerHTML = '<div class="answer-box" id="streamAnswer"></div>';
                const streamDiv = document.getElementById('streamAnswer');
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    
                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.substring(6));
                                
                                if (data.content) {
                                    answer += data.content;
                                    streamDiv.textContent = answer;
                                } else if (data.context) {
                                    contextData = data;
                                }
                            } catch (e) {
                                // Ignore JSON parse errors
                            }
                        }
                    }
                }
                
                // 添加上下文信息
                if (contextData && contextData.context) {
                    let contextHTML = '<div class="context-box"><strong>📖 检索到的相关内容：</strong><br><br>';
                    contextData.context.forEach((ctx, idx) => {
                        contextHTML += `
                            <div class="context-item">
                                <strong>文本块 ${idx + 1}</strong> (相似度: ${(ctx.similarity * 100).toFixed(2)}%)<br>
                                <small>来源: ${ctx.document}</small><br>
                                <div style="margin-top: 5px; color: #666;">${ctx.text.substring(0, 150)}...</div>
                            </div>
                        `;
                    });
                    contextHTML += '</div>';
                    answerBox.innerHTML += contextHTML;
                }
                
            } catch (error) {
                answerBox.innerHTML = `<div class="status error">❌ 错误: ${error.message}</div>`;
            }
        }
        
        // 页面加载时检查状态
        window.onload = function() {
            checkStatus();
        };
    </script>
</body>
</html>

